package com.luo.bbs.ums.webapi.controller;

import com.google.gson.Gson;
import com.luo.common.restful.JsonResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 七牛云上传
 */
@RestController
@RequestMapping("/api/upload")
@Slf4j
public class QiniuController {

    @PostMapping("/picture1")
    public JsonResult uploadPicture(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("进入上传");
        String qiniuUrl = "rqptdeipt.hn-bkt.clouddn.com";//外链域名
        Configuration configuration = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(configuration);
        String accessKey = "IzlTRIW54hy7L73kHI5zhbvcZ5pipeDLpap89aJk";
        String secretKey = "GvacpfM1zI9hAFXbgKKYfFn3oySMvcoxoWhuB0mL";
        String bucket = "amagi";//存储空间名称
        String key =null;//自动生成随机文件名
        Auth auth = Auth.create(accessKey,secretKey);
        String uptoken = auth.uploadToken(bucket);
        String responseUrl = "";
        try{
            byte[] localFile = file.getBytes();
            Response response = uploadManager.put(localFile,key,uptoken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            responseUrl = "http://"+ qiniuUrl + "/"+ putRet.key;
            log.info("上传成功");
        }catch (QiniuException e){
            Response r = e.response;
        }
        return JsonResult.ok(responseUrl);

    }

}
